const express = require('express');
const cors = require('cors');
const compression = require('compression');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 6359;

// 中间件
app.use(cors());
app.use(compression());

// 在静态文件服务之前设置所有MIME类型
app.use((req, res, next) => {
    if (req.url.endsWith('.js')) {
        res.type('application/javascript');
    } else if (req.url.endsWith('.json')) {
        res.type('application/json');
    } else if (req.url.endsWith('.b3dm')) {
        res.type('application/octet-stream');
    } else if (req.url.endsWith('.glb')) {
        res.type('model/gltf-binary');
    } else if (req.url.endsWith('.gltf')) {
        res.type('model/gltf+json');
    }
    next();
});

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 模型文件路由 - 为models1, models2, models3添加支持
app.use('/models', express.static(path.join(__dirname, 'models')));
// app.use('/models1', express.static(path.join(__dirname, 'models1')));
app.use('/models2', express.static(path.join(__dirname, 'models2')));
app.use('/models3', express.static(path.join(__dirname, 'models3')));
// app.use('/models4', express.static(path.join(__dirname, 'models4')));
// app.use('/models5', express.static(path.join(__dirname, 'models5')));
app.use('/models6', express.static(path.join(__dirname, 'models6')));




// 图片文件路由
app.use('/img', express.static(path.join(__dirname, 'img')));

// 确保所有其他路由都返回 index.html（这应该是最后的fallback）
app.get('*', (req, res) => {
    // 只有当请求不是静态资源时才返回index.html
    if (!req.url.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg|json|b3dm|glb|gltf)$/)) {
        res.sendFile(path.join(__dirname, 'public', 'index.html'));
    } else {
        res.status(404).send('File not found');
    }
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log(`Visit http://localhost:${PORT} to view the application`);
    console.log('Static file routes:');
    console.log('  /models  -> ./models/');
    console.log('  /models1 -> ./models1/');
    console.log('  /models2 -> ./models2/');
    console.log('  /models3 -> ./models3/');
    console.log('  /img     -> ./img/');
}); 